import peerDepsExternal from "rollup-plugin-peer-deps-external";
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "rollup-plugin-typescript2";
import postcss from "rollup-plugin-postcss";
import json from "@rollup/plugin-json";
const { babel } = require("@rollup/plugin-babel");
const packageJson = require("./package.json");
const less = require("less");
import * as fs from 'fs'
import * as path from 'path'
import css from 'rollup-plugin-css-only'

const isProd = process.env.NODE_ENV === "production";

const entry = 'packages/index.ts'
const componentsDir = 'packages'
const componentsName = fs.readdirSync(path.resolve(componentsDir))
const componentsEntry = componentsName.map(
  (name) => `${componentsDir}/index.ts`
)
const esmOutput = {
  preserveModules: true,
  preserveModulesRoot: 'src',
  exports: 'auto',
  // assetFileNames: ({ name }) => {
  //   const { ext, dir, base } = path.parse(name);
  //   print(name, ext, dir, base)
  //   if (ext !== '.less') return '[name].[ext]';
  //   // 规范 style 的输出格式
  //   return path.join(dir, 'style', base);
  // }
}

const babelOptions = {
  presets: ["@babel/preset-env"],
  extensions: ['.tsx', '.js', '.jsx', '.ts','.less'],
  exclude: "**/node_modules/**"
};

const processLess = function(context, payload) {
  debugger

  return new Promise((resolve, reject) => {
    less.render(
      {
        file: context
      },
      function(err, result) {
        if (!err) {
          resolve(result);
        } else {
          reject(err);
        }
      }
    );
    less.render(context, {}).then(
      function(output) {
        if (output && output.css) {
          resolve(output.css);
        } else {
          reject({});
        }
      },
      function(err) {
        reject(err);
      }
    );
  });
};

export default {
  // input: "packages/index.ts",
  // output: [
  //   {
  //     dir: 'build/es/index.js',//packageJson.main,
  //     exports: 'auto',
  //     format: "cjs",
  //     preserveModules: true
  //   },
  //   {
  //     dir: 'build/module/index.js',
  //     exports: 'auto',
  //     format: "es",
  //     preserveModules: true
  //   },
  // ],
  input: [entry, ...componentsEntry],
        output: {...esmOutput, dir: 'build/es/', format: 'es',  preserveModules: true,},
  external: ['react', 'react-dom', 'classnames', 'antd'],
  plugins: [
    peerDepsExternal({ includeDependencies: !isProd }),
    resolve(),
    commonjs({ sourceMap: !isProd }),
    typescript({ useTsconfigDeclarationDir: false }),
    postcss({
      extract: true,
      process: processLess
    }),
    babel(babelOptions),
    json(),
    css({
      output: function (styles, styleNodes) {
            console.log(styleNodes)
            fs.writeFileSync('dist/style.css', styles)
          }
  })
  ],
};
